package repository

import (
	"gitee.com/ysl729895/go-mall/internal/model"
	"gorm.io/gorm"
)

// UserRoleRepository 用户-角色关联数据操作接口
//go:generate mockgen -source=user_role_repository.go -destination=mock_user_role_repository.go -package=repository

type UserRoleRepository interface {
	Create(userRole *model.UserRole) error
	DeleteByUserID(userID uint) error
	GetRolesByUserID(userID uint) ([]model.Role, error)
}

type userRoleRepository struct {
	db *gorm.DB
}

func NewUserRoleRepository(db *gorm.DB) UserRoleRepository {
	return &userRoleRepository{db: db}
}

func (r *userRoleRepository) Create(userRole *model.UserRole) error {
	return r.db.Create(userRole).Error
}

func (r *userRoleRepository) DeleteByUserID(userID uint) error {
	return r.db.Where("user_id = ?", userID).Delete(&model.UserRole{}).Error
}

func (r *userRoleRepository) GetRolesByUserID(userID uint) ([]model.Role, error) {
	var roles []model.Role
	err := r.db.Table("user_roles").Select("roles.*").Joins("left join roles on user_roles.role_id = roles.id").Where("user_roles.user_id = ?", userID).Scan(&roles).Error
	return roles, err
}
